import { DependencyContainer, toSuccess, useTransaction } from '@sker/core';
import { KsLiveRoom, KsRedPacket } from '@sker/entities';
import { useData } from '@sker/runtime';
import dayjs from 'dayjs';
import { z } from 'zod';
export function getDefaultCount(type: string): number {
    switch (type) {
        case '口令':
            return 80
        case '粉丝包':
            return 2;
        case '快币':
            return 100;
        case '分享':
            return 2;
        case '穿云箭':
            return 200;
        default:
            return 1000;
    }
}
export default async (injector: DependencyContainer) => {
    const input = z.object({
        type: z.optional(z.string()),
        uuid: z.string(),
        count: z.optional(z.any())
    })
    const body = input.parse(useData())
    body.type = body.type || `口令`
    body.count = body.count ? parseInt(`${body.count}`) : getDefaultCount(body.type)
    if (body.type === '口令') {
        body.count = 60;
    }
    const list = await useTransaction(async m => {
        // 获取房间信息
        const sql = await m.createQueryBuilder()
            .select('red.count', 'count')
            .addSelect('red.id', 'id')
            .addSelect('room.link', 'link')
            .addSelect('room.open_time', 'open_time')
            .addSelect('red.room_id', 'room_id')
            .addSelect('room.user_id', 'user_id')
            .addSelect('room.name', 'name')
            .addSelect('room.in_room_count', 'in_room_count')
            .addSelect('room.online', 'online')
            .leftJoin(KsLiveRoom, 'room', 'room.id=red.room_id')
            .from(KsRedPacket, 'red')
            .where('red.type =:type', { type: body.type })
            // .andWhere('room.open_time>:start and room.open_time<:end', {
            //     start, end
            // })
            .andWhere('room.open_time>=:start and room.open_time<=:end', {
                start: dayjs().add(60 * 2, 'second').toDate(),
                end: dayjs().add(60 * 5, 'second').toDate()
            })
            .andWhere('red.count>:count', { count: body.count })
            .andWhere('room.in_room_count<:in_room_count', { in_room_count: 7 })
            .orderBy(`red.count`, 'DESC')
            .addOrderBy(`room.in_room_count`, 'ASC')

        const list = await sql.execute()
        const set = new Set(list.map(it => it.user_id))
        const allList = [...set].map(link => {
            return list.find(it => it.user_id === link)
        });
        if (allList.length > 0) {
            return [...allList.map(it => {
                it.money_v = parseInt(`${100 * it.count * Math.sqrt(it.count) / it.online}`) / 100;
                return it;
            }).sort((a, b) => b.money_v - a.money_v)];
        }
        return []
    })
    return toSuccess(list)
}
